import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yurun_smartmerchants/generated/json/base/json_convert_content.dart';
import 'package:yurun_smartmerchants/global.dart';
import 'package:yurun_smartmerchants/models/login_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/net/NetUtil.dart';
import 'package:yurun_smartmerchants/page/verify_code.dart';
import 'package:yurun_smartmerchants/routes/routes.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  var usernameController = new TextEditingController();
  var pwdController = new TextEditingController();

  bool errorCode = false;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        alignment: Alignment.topCenter,
        children: <Widget>[
          Positioned(
              top: 0,
              child: Image.asset(
                'images/bg_login.png',
                fit: BoxFit.cover,
              )),
          Positioned(
              top: AppSize.height(155),
              child: Image.asset(
                'images/logo.png',
                width: AppSize.width(396),
                height: AppSize.height(206),
              )),
          Positioned(
              top: AppSize.height(498),
              left: AppSize.width(71),
              right: AppSize.width(71),
              child: TextField(
                controller: usernameController,
                keyboardType: TextInputType.phone,
                maxLength: 11,
                inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
                onChanged: (value) {
                  setState(() {});
                },
                decoration: InputDecoration(
                  hintStyle: TextStyle(fontSize: AppSize.sp(32), color: Colors.grey),
                  hintText: '请输入手机号',
                  prefixIcon: Icon(
                    Icons.phone_android,
                    color: Colors.grey,
                  ),
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: const Color(0xffdd4b39)),
                  ),
                ),
              )),
          Positioned(
              top: AppSize.height(620),
              left: AppSize.width(71),
              right: AppSize.width(71),
              child: TextField(
                controller: pwdController,
                obscureText: true,
                keyboardType: TextInputType.number,
                maxLength: 6,
                inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
                decoration: InputDecoration(
                  hintStyle: TextStyle(fontSize: AppSize.sp(32), color: Colors.grey),
                  hintText: '请输入验证码',
                  errorText: errorCode ? '您输入的验证码不正确' : null,
                  errorStyle: TextStyle(fontSize: AppSize.sp(24)),
                  prefixIcon: Icon(
                    Icons.verified_user,
                    color: Colors.grey,
                  ),
//                  suffixIcon: Offstage(
//                    offstage: false,
//                    child: Padding(padding: EdgeInsets.only(top: AppSize.height(18)),child: ResetCodePage(onTapCallback:(){},phoneNum: phoneNumber),),
//                  ),
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey),
                  ),
                  focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: const Color(0xffdd4b39)),
                  ),
                ),
              )),
          Positioned(
              top: AppSize.height(620),
              right: AppSize.width(71),
              child: Padding(
                padding: EdgeInsets.only(top: AppSize.height(18)),
                child: ResetCodePage(
                  phoneNum: usernameController.text,
                ),
              )
          ),
          Positioned(
              top: AppSize.height(795),
              left: AppSize.width(71),
              right: AppSize.width(71),
              child: RaisedButton(
                color: const Color(0xffdd4b39),
                onPressed: () {
                  String phone = usernameController.text;
                  String code = pwdController.text;

                  if (phone.isEmpty || phone == null) {
                    showToast('手机号不能为空');
                  } else if (code.isEmpty || code == null) {
                    showToast('验证码不能为空');
                  } else {
                    _login(phone, code);
                    setState(() {
                      errorCode = false;
                    });
                  }
                },
                child: Padding(
                  padding: EdgeInsets.only(top: 15, bottom: 15),
                  child: Text(
                    '登录',
                    style: TextStyle(color: Colors.white, fontSize: AppSize.sp(32)),
                  ),
                ),
              )),
          Positioned(
              top: AppSize.height(913),
              child: Text(
                '未注册的手机号验证后自动创建账户',
                style: TextStyle(color: const Color(0xff626262), fontSize: AppSize.sp(24)),
              )),
          Positioned(
              top: AppSize.height(1200),
              child: Row(
                children: <Widget>[
                  Text(
                    '登录/注册即表示同意',
                    style:
                        TextStyle(color: const Color(0xff626262), fontSize: AppSize.sp(24)),
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, protocol_page);
                    },
                    child: Text(
                      '《用户协议和隐私政策》',
                      style: TextStyle(
                          color: const Color(0xffdd4b39), fontSize: AppSize.sp(24)),
                    ),
                  )
                ],
              ))
        ],
      ),
    );
  }

  void _login(String phoneNum,String verifyCode){
    LoadingUtil.showLoading(context, tip: '登录中...');
    ApiInterface.login(phoneNum, verifyCode).then((value){
      LoadingUtil.hideLoading(context);
      LoginEntity loginEntity = JsonConvert.fromJsonAsT<LoginEntity>(value);
      Global.prefs.setString(Global.url_avatar, loginEntity.accountDto.url);
      Global.prefs.setString(Global.token, loginEntity.token);
      if(loginEntity.accountDto.consumerId.toString().isEmpty || loginEntity.accountDto.consumerId == null){
//        Navigator.of(context).pushNamed(personal_information_page);
      Navigator.pushNamed(context, personal_information_page);
      }else {
        Global.prefs.setString(Global.consumer_id, loginEntity.accountDto.consumerId.toString());
        Navigator.pushNamedAndRemoveUntil(context, home_page, (route) => false);
      }
    }).catchError((error){
      LoadingUtil.hideLoading(context);
      if(error is LogicError){
        setState(() {
          errorCode = true;
        });
      }
    });
  }

  @override
  void dispose() {
    usernameController.dispose();
    pwdController.dispose();
    // TODO: implement dispose
    super.dispose();
  }
}
